<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.go(-1)" />
    <div class="sear">
      <van-search
        v-model.trim="keyword"
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        @input="oninput"
      >
        <template #action>
          <div
            @click="$router.push({ path: '/searchResult', query: { keyword } })"
          >
            搜索
          </div>
        </template>
      </van-search>
    </div>
    <div class="cell-item">
      <van-cell-group>
        <van-cell
          v-for="(item, index) in showReg"
          :key="index"
          icon="search"
          @click="
            $router.push({
              path: '/searchResult',
              query: { keyword: searchList[index] }
            })
          "
        >
          <template #title>
            <div v-html="item"></div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <div class="lishi">
      <van-cell-group>
        <van-cell title="历史记录" />
        <van-cell
          :title="item"
          v-for="(item, index) in sousuoLishi"
          :key="index"
        >
          <van-icon name="close" @click="delClick" />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { searchInput, searchLiShi, delSearchList } from './home'
export default {
  name: 'search',
  data () {
    return {
      keyword: '', // 搜索关键字
      searchList: [], //推荐列表
      sousuoLishi: [],
      timeId: null
    }
  },
  async created () {
    let res = await searchLiShi()
    console.log(res)
    this.sousuoLishi = res.data.data.keywords
  },
  methods: {
    oninput () {
      // 检查关键字为不为空
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.keyword == '') {
          this.searchList = []
          return
        }
        const res = await searchInput(this.keyword)
        this.searchList = res.data.data.options
      }, 500)
    },
    async delClick () {
      let res = await delSearchList()
      this.$dialog
        .confirm({
          title: '温馨提示',
          message: '确定要删除吗?'
        })
        .then(() => {
          this.sousuoLishi = []
        })
        .catch(() => {
          console.log('1')
        })
    }
  },
  computed: {
    showReg () {
      const reg = new RegExp(this.keyword, 'gi')
      return this.searchList.map(value =>
        value.replace(reg, match => `<span style='color:red'>${match}</span>`)
      )
    }
  }
}
</script>

<style lang="less">
.search {
  .van-nav-bar .van-icon {
    color: cornflowerblue;
  }
}
</style>
